package UDP;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

public class NIOUDPServer {
     Vector<String>ips;
     Vector<String>names;

     public void Run() {
        try {
            Selector selector = Selector.open();

            DatagramChannel server = DatagramChannel.open();
            server.bind(new InetSocketAddress("localhost",6666));//绑定端口
            server.configureBlocking(false);//非阻塞
            server.register(selector, SelectionKey.OP_READ);//监听信息

            while(true){
                //无事可做
                selector.select();
                //病人呼叫
                Set<SelectionKey> set = selector.selectedKeys();//病人集合
                //护士查看
                Iterator<SelectionKey> it = set.iterator();
                while(it.hasNext()){
                    //灭灯
                    SelectionKey key = it.next();
                    it.remove();
                    //处理
                    if(key.isReadable()){//发送数据
                        DatagramChannel datagramChannel = (DatagramChannel) key.channel();

                        ByteBuffer data = ByteBuffer.allocate(8 * 1024);
                        System.out.println("数据包源地址" + datagramChannel.receive(data));
                        int pos = data.position();
                        data.flip();
                        System.out.println(new String(data.array(),0, pos));

                    }

                }
            }

        } catch (Exception e){
            e.printStackTrace();
        }

    }
}
